package com.lianxi.Courses.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lianxi.Courses.constant.DictConstant;
import com.lianxi.Courses.constant.StatusConstant;
import com.lianxi.Courses.dao.ChapterMapper;
import com.lianxi.Courses.dao.ResourceMapper;
import com.lianxi.Courses.entity.*;
import com.lianxi.Courses.exception.ChapterExistException;
import com.lianxi.Courses.exception.CourseExistException;
import com.lianxi.Courses.exception.FileUploadErrorException;
import com.lianxi.Courses.exception.RequestParameterErrorException;
import com.lianxi.Courses.service.ChapterService;
import com.lianxi.Courses.util.ParameterUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class ChapterServiceImpl implements ChapterService {
    @Autowired
    private ChapterMapper chapterMapper;
    @Autowired
    private ResourceMapper resourceMapper;



//    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
//    @Override
//    public PageInfo<Chapter> findPage(Chapter chapterParam, String pageNo, String pageSize) {
//        if (ParameterUtil.isNull(pageNo)) {
//            pageNo = DictConstant.CHAPTER_DEFAULT_PAGE_NO;
//        }
//        if (ParameterUtil.isNull(pageSize)) {
//            pageSize = DictConstant.CHAPTER_DEFAULT_PAGE_SIZE;
//        }
//
//        PageHelper.startPage(Integer.parseInt(pageNo), Integer.parseInt(pageSize));
//        List<Chapter> chapters = chapterMapper.selectAll(chapterParam);
//        PageInfo<Chapter> chapterPage = new PageInfo<>(chapters);
//        return chapterPage;
//}



    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public PageInfo<Chapter> findPage(Chapter chapterParam, String pageNo, String pageSize) {
        if (ParameterUtil.isNull(pageNo)) {
            pageNo = DictConstant.CHAPTER_DEFAULT_PAGE_NO;
        }
        if (ParameterUtil.isNull(pageSize)) {
            pageSize = DictConstant.CHAPTER_DEFAULT_PAGE_SIZE;
        }

        PageHelper.startPage(Integer.parseInt(pageNo), Integer.parseInt(pageSize));
        List<Chapter> chapters = chapterMapper.selectAll(chapterParam);

        for (Chapter chapter : chapters) {
            ResourceExample resourceExample = new ResourceExample();
            resourceExample.or().andChapterIdEqualTo(chapter.getId());
            List<Resource> resources = resourceMapper.selectByExample(resourceExample);

            chapter.setResources(resources);

            if (!resources.isEmpty()) {
                chapter.setResource(resources.get(0));
            }
        }

        PageInfo<Chapter> chapterPage = new PageInfo<>(chapters);
        return chapterPage;
    }






    @Override
    public void addChapter(String title, String info, CommonsMultipartFile file, String resourceTitle, String costType, String costNum, Date createDate, String fileType,
                           HttpSession session, Integer courseId) throws RequestParameterErrorException, ChapterExistException, FileUploadErrorException {
        try {
            Integer.parseInt(costNum);
        } catch (NumberFormatException e) {
            throw new RequestParameterErrorException("花费值必须为数字");
        }

        if (ParameterUtil.isNull(title) || ParameterUtil.isNull(info) || file.isEmpty() ||
                ParameterUtil.isNull(resourceTitle) || ParameterUtil.isNull(costType) ||
                ParameterUtil.isNull(costNum) || ParameterUtil.isNull(fileType) || courseId == null) {
            throw new RequestParameterErrorException("请求参数有误");
        }



        // 添加文件格式验证
        String filename = file.getOriginalFilename();
        if (filename == null || filename.lastIndexOf(".") == -1) {
            throw new RequestParameterErrorException("文件名格式不正确");
        }

        String extension = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
        if (!"mp4".equals(extension) && !"pdf".equals(extension)) {
            throw new RequestParameterErrorException("只能上传MP4和PDF格式的文件");
        }




        ChapterExample example = new ChapterExample();
        example.or()
                .andTitleEqualTo(title)
                .andCourseIdEqualTo(courseId);
        List<Chapter> chapters = chapterMapper.selectByExample(example);
        if (!chapters.isEmpty()) {
            throw new ChapterExistException("该课程下已存在同名章节");
        }
        Chapter chapter = new Chapter();
        chapter.setTitle(title);
        chapter.setInfo(info);
        chapter.setCourseId(courseId);
        chapter.setCreateDate(createDate != null ? createDate : new Date());
        chapter.setStatus(1);

        chapterMapper.insertSelective(chapter);


        String dateFolder = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String relativePath = "/upload/chapter/" + dateFolder;
        String realPath = session.getServletContext().getRealPath(relativePath);

        File dir = new File(realPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        String filePath = relativePath + "/" + filename;

        try {
            File targetFile = new File(dir, filename);
            file.transferTo(targetFile);
        } catch (Exception e) {
            throw new FileUploadErrorException("文件上传失败，请重试");
        }


        Resource resource = new Resource();
        resource.setTitle(resourceTitle);
        resource.setOriginalName(filename);
        resource.setPath(filePath);
        resource.setCoverImageUrl(filePath);
        resource.setFileType(fileType);
        resource.setCostType(Integer.valueOf(costType));
        resource.setCostNumber(Integer.valueOf(costNum));
        resource.setCreateDate(createDate != null ? createDate : new Date());
        resource.setStatus(1);
        resource.setChapterId(chapter.getId());
        resource.setFileSize((int) file.getSize());
        resource.setClickCount(0);

        resourceMapper.insertSelective(resource);
    }

    @Override
    public void modifyChapter(String id, String title, String info, CommonsMultipartFile file, String resourceTitle, String costType, String costNum, Date createDate, String fileType, HttpSession session, Integer courseId) throws RequestParameterErrorException, ChapterExistException, FileUploadErrorException {
        try {
            Integer.parseInt(costNum);
        } catch (NumberFormatException e) {
            throw new RequestParameterErrorException("花费值必须为数字");
        }

        if (ParameterUtil.isNull(title) || ParameterUtil.isNull(info) ||
                ParameterUtil.isNull(resourceTitle) || ParameterUtil.isNull(costType) ||
                ParameterUtil.isNull(costNum) || ParameterUtil.isNull(fileType) || courseId == null) {
            throw new RequestParameterErrorException("请求参数有误");
        }



        if (file != null && !file.isEmpty()) {
            String filename = file.getOriginalFilename();
            if (filename == null || filename.lastIndexOf(".") == -1) {
                throw new RequestParameterErrorException("文件名格式不正确");
            }

            String extension = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
            if (!"mp4".equals(extension) && !"pdf".equals(extension)) {
                throw new RequestParameterErrorException("只能上传MP4和PDF格式的文件");
            }
        }



        Chapter chapter = chapterMapper.selectByPrimaryKey(Integer.parseInt(id));

        if (chapter == null) {
            throw new RequestParameterErrorException("要修改的章节不存在");
        }

        chapter.setTitle(title);
        chapter.setInfo(info);
        chapter.setCreateDate(createDate != null ? createDate : new Date());
        chapterMapper.updateByPrimaryKeySelective(chapter);

        ResourceExample resourceExample = new ResourceExample();
        resourceExample.or().andChapterIdEqualTo(chapter.getId());
        List<Resource> resources = resourceMapper.selectByExample(resourceExample);

        Resource resource = resources.isEmpty() ? new Resource() : resources.get(0);

        if (file != null && !file.isEmpty()) {
            String filename = file.getOriginalFilename();
            String dateFolder = new SimpleDateFormat("yyyyMMdd").format(new Date());
            String relativePath = "/upload/chapter/" + dateFolder;
            String realPath = session.getServletContext().getRealPath(relativePath);

            File dir = new File(realPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            String filePath = relativePath + "/" + filename;

            try {
                File targetFile = new File(dir, filename);
                file.transferTo(targetFile);
                resource.setOriginalName(filename);
                resource.setPath(filePath);
                resource.setCoverImageUrl(filePath);
                resource.setFileSize((int) file.getSize());
            } catch (Exception e) {
                throw new FileUploadErrorException("文件上传失败，请重试");
            }
        }

        resource.setTitle(resourceTitle);
        resource.setFileType(fileType);
        resource.setCostType(Integer.valueOf(costType));
        resource.setCostNumber(Integer.valueOf(costNum));
        resource.setCreateDate(createDate != null ? createDate : new Date());
        resource.setStatus(1);
        resource.setChapterId(chapter.getId());

        if (resources.isEmpty()) {
            resource.setClickCount(0);
            resourceMapper.insertSelective(resource);
        } else {
            resourceMapper.updateByPrimaryKeySelective(resource);
        }
    }




    @Override
    public void modifyStatus(String id, String status) throws RequestParameterErrorException {
        if (ParameterUtil.isNull(id) || ParameterUtil.isNull(status)) {
            throw new RequestParameterErrorException("请求参数有误");
        }
        Chapter chapter = new Chapter();
        chapter.setId(Integer.parseInt(id));
        chapter.setStatus(Integer.parseInt(status));
        if (chapter.getStatus() == StatusConstant.CHAPTER_STATUS_ENABLED) {
            chapter.setStatus(StatusConstant.CHAPTER_STATUS_DISABLED);
        } else {
            chapter.setStatus(StatusConstant.CHAPTER_STATUS_ENABLED);
        }
        chapterMapper.updateByPrimaryKeySelective(chapter);
    }

    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    @Override
    public Chapter findById(String id) throws RequestParameterErrorException {
        if (ParameterUtil.isNull(id)) {
            throw new RequestParameterErrorException("请求参数有误");
        }
        Chapter chapter = chapterMapper.selectWithCourseById(Integer.parseInt(id));
        if (chapter != null) {
            ResourceExample resourceExample = new ResourceExample();
            resourceExample.or().andChapterIdEqualTo(chapter.getId());
            List<Resource> resources = resourceMapper.selectByExample(resourceExample);
            if (!resources.isEmpty()) {
                chapter.setResource(resources.get(0));
            }
        }
        return chapter;
    }

    @Override
    public List<Chapter> findByCourseId(Integer courseId) throws RequestParameterErrorException {
        if (ParameterUtil.isNull(String.valueOf(courseId))) {
            throw new RequestParameterErrorException("请求参数有误");
        }
        ChapterExample chapterExample = new ChapterExample();
        chapterExample.or().andCourseIdEqualTo(courseId);
        List<Chapter> chapters = chapterMapper.selectByExample(chapterExample);
        if (!chapters.isEmpty()) {
            return chapters;
        }
        return null;
    }


}
